#ifndef PATHSMOOTHINGCA_H
#define PATHSMOOTHINGCA_H

#include <vector>
#include <cstdio>
#include <QDebug>
#include "ca.h"
#include "rules/PathSmoothing.h"
#include "neighbourhoods/moore_1.h"

class PathSmoothingCA:public CA
{

public:

    PathSmoothingCA():CA()
    {

    }
    ~PathSmoothingCA()
    {
        delete current_states;
        delete new_states;
    }


    bool next()
    {
        bool changed=false;
        for(int i=0;i<current_states->size(1);++i)
            for(int j=0;j<current_states->size(0);++j){
                new_states->set(current_states->get(i,j),i,j);
                std::vector<int> nbs=mn::neighbours(current_states,i,j);

                for(int r=0;r<psr::RULES_SIZE;++r)
                {
                    bool f=true;
                    if(current_states->get(i,j)!=EMPTY)break;
                    for(int n=0;n<psr::NEIGHBOURS_SIZE;++n)
                    {

                        if(psr::rules[r][n+1]!=ANY && nbs[n]!=psr::rules[r][n+1])
                        {
                            f=false;
                            break;
                        }
                    }
                    if(f)
                    {

                        int new_state=psr::rules[r][psr::NEIGHBOURS_SIZE+1];
                        changed=(new_states->get(i,j)!=new_state);
                        if(changed)new_states->set(new_state,i,j);
                        break;

                    }
                    if(changed)break;
                }
                if(changed)break;
            }

        Grid* tmp=new_states;
        new_states=current_states;
        current_states=tmp;
        ++step;
        return changed;

    }

    void start(){
        while(next());
    }

    void start(int steps)
    {
        for(int i=0;i<steps;++i)next();
    }

    int getStep()const
    {
        return step;
    }


    Grid* grid_copy()const
    {
        return current_states->copy();
    }

    void set(const Grid& grid)
    {
        this->step=0;
        this->current_states =grid.copy();
        this->new_states = grid.copy();
    }


};




#endif // PATHSMOOTHINGCA_H
